<template>
  <!-- 页面容器 -->
  <div class="app-container">
    <!-- 表单容器 -->
    <div class="common-container">
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="max-width: 600px; padding: 20px"
        @submit.native.prevent="submitForm"
      >
        <!-- 数据源类型 -->
        <el-form-item label="数据源连接类型" prop="dataSourceType">
          <el-select v-model="formData.dataSourceType" placeholder="请选择">
            <!-- <el-option v-for="item in dataSourceTypeOptions" :key="item.value" :label="item.label"
              :value="item.value" /> -->
            <el-option
              v-for="(value, label) in typeOptions"
              :key="label"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <!-- 数据源连接名称 -->
        <el-form-item label="数据源连接名称">
          <el-input v-model="formData.aliasName" placeholder="请输入" clearable />
        </el-form-item>

        <!-- 数据源连接名称 -->
        <el-form-item label="数据库名称">
          <el-input v-model="formData.dataSourceName" placeholder="请输入" clearable />
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="数据源描述" prop="dataSourceDescription">
          <el-input v-model="formData.dataSourceDescription" />
        </el-form-item>

        <!-- 数据源地址 -->
        <el-form-item label="数据源连接地址">
          <el-input v-model="formData.dataSourceAddress" placeholder="请输入" clearable />
        </el-form-item>

        <!-- 端口 -->
        <el-form-item label="端口">
          <el-input v-model="formData.dataSourcePort" placeholder="请输入" clearable />
        </el-form-item>

        <!-- 数据库名称 -->
        <!-- <el-form-item label="数据库名称">
          <el-input v-model="formData.databaseName" placeholder="请输入" clearable />
        </el-form-item> -->

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="dataSourceUserName" placeholder="请输入">
          <el-input v-model="formData.dataSourceUserName" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="dataSourcePassword">
          <el-input v-model="formData.dataSourcePassword" type="password" show-password />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="success" :loading="loading" @click="testConnect">测试连接</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import NewDataSourceAPI, { dataSourceForm } from "@/api/dataSourceManage/createDataSource";

export default defineComponent({
  name: "DataSourceForm",
  emits: ["close", "success"],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref<FormInstance>();

    // 表单数据
    const formData = reactive<dataSourceForm>({
      // 创建人
      createUser: "",
      // 创建人id
      createUserId: 0,
      // 数据源类型
      dataSourceType: 1,
      //数据源名称
      aliasName: "",
      // 数据库名称
      dataSourceName: "",
      // 数据源描述
      dataSourceDescription: "",
      // 数据源地址
      dataSourceAddress: "",
      // 数据源端口
      dataSourcePort: 3306,
      // 数据库名称
      databaseName: "",
      // 数据源用户名
      dataSourceUserName: "",
      // 数据源密码
      dataSourcePassword: "",
    });

    const typeData = {
      MYSQL: 1,
      HIVE: 2,
    };

    const typeOptions = ref(typeData);

    // 表单校验规则
    const formRules = {
      dataSourceName: [{ required: true, message: "请选择数据源名称", trigger: "change" }],
      dataSourceType: [{ required: true, message: "请选择数据源类型", trigger: "change" }],
      dataSourceAddress: [{ required: true, message: "请选择数据源地址", trigger: "change" }],
      dataSourcePort: [{ required: true, message: "请选择端口", trigger: "change" }],
      dataSourceUserName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      dataSourcePassword: [{ required: true, message: "请输入密码", trigger: "blur" }],
      databaseName: [{ required: true, message: "请输入数据库名称", trigger: "blur" }],
    };
    // 下拉选项数据
    const dataSourceTypeOptions = ref([]);

    // 加载状态
    const loading = ref(false);

    // 获取下拉选项数据
    // const fetchOptions = async () => {
    //   loading.value = true;
    //   try {
    //     const data = await NewDataSourceAPI.getOptions(9); // 假设 id 为 9
    //     dataSourceTypeOptions.value = data.dataSourceType;
    //   } catch (error) {
    //     console.error("获取选项失败：", error);
    //     ElMessage.error("获取选项失败，请稍后重试");
    //   } finally {
    //     loading.value = false;
    //   }
    // };

    const testConnect = async () => {
      try {
        // 表单校验
        const valid = await formRef.value.validate();
        if (!valid) return;

        loading.value = true;
        ElMessage.success("连接成功");
        await NewDataSourceAPI.insertTest(formData);
      } catch (error: any) {
        ElMessage.error(`${error.message}`);
      } finally {
        loading.value = false;
      }
    };
    // 提交表单
    const submitForm = async () => {
      try {
        // 表单校验
        const valid = await formRef.value.validate();
        if (!valid) return;

        loading.value = true;
        await NewDataSourceAPI.add(formData); // 调用接口提交数据
        ElMessage.success("新增成功");
        emit("success");
        cleanForm(); // 清空表单
      } catch (error: any) {
        console.error("提交失败：", error);
        ElMessage.error(`操作失败：${error.message}`);
      } finally {
        loading.value = false;
      }
    };

    // 清空表单
    const cleanForm = () => {
      formRef.value.resetFields(); // 使用 Element Plus 提供的 resetFields 方法
    };
    //取消
    const handleCancel = () => {
      cleanForm();
      ElMessage.info("已取消操作");
      emit("close");
    };

    // 组件挂载时获取选项数据，暂时停用该请求
    // onMounted(fetchOptions);

    return {
      typeOptions,
      formRef,
      formData,
      formRules,
      dataSourceTypeOptions,
      loading,
      submitForm,
      handleCancel,
      testConnect,
    };
  },
});
</script>

<style lang="scss" scoped>
.common-container {
  width: 100%;
  max-width: 600px;
  padding: 18px 0 0 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}
</style>
